const xml2js = require('xml2js');
var csv = require('fast-csv');
const fs = require('fs');

function parseCSVFile(responseString, delimiter, callback) {
  var data = [];

  var options = {
    delimiter: delimiter,
    headers: true,
    discardUnmappedColumns: true,
    quote: null,
    ignoreEmpty: true,
    trim: true
  };

  // Remove all instances of double newlines
  responseString = responseString.replace(/\n\n/g, '');

  return csv.fromString(responseString, options)
    .on('data', function (value) {
      data.push(value);
    })
    .on('end', function () {
      var items = {};
      items.data = data;
      return callback(null, items);
    })
    .on('error', function (error) {
      debug('error ', error);
      return callback(error);
    });
}

const AmazonMwsStub = function(action, xmlPath) {
  const responseString = fs.readFileSync(xmlPath, 'utf8');
  this.mockupCommaDelimiteReport = async function(sellerId, mwsAuthToken, marketplaceidList) {
    const headers = {
      "server": "Server",
      "date": "Sun, 16 Aug 2020 03:30:58 GMT",
      "content-type": "text/plain;charset=Cp1252",
      "content-length": "961",
      "connection": "close",
      "x-amz-rid": "WGWXM1ENR56CVDYS0XQS",
      "x-mws-quota-max": "60.0",
      "x-mws-quota-remaining": "57.0",
      "x-mws-quota-resetson": "2020-08-16T04:09:00.000Z",
      "content-md5": "GUhXEnqSAjqE4ay1XDdkUA==",
      "x-mws-response-context": "aOsN4kFxkvluCLHKBSBLOltUkgFzZjCaYJ25ykDFcsVW0cVvPp3DLXvt6eIYdjJn/qyny5gg/6o=, ps1Q0/mukl/acPWAdzJyIkYt0CrrIQ19xgddunEFmLEzy7BpQxAPkRkfTQeO5gdKFTUstCZQTRI=",
      "x-amz-request-id": "f50fdd9f-ac49-467d-859c-a49f40575861",
      "x-mws-request-id": "f50fdd9f-ac49-467d-859c-a49f40575861",
      "x-mws-timestamp": "2020-08-16T03:30:58.488Z",
      "vary": "Content-Type,Accept-Encoding,X-Amzn-CDN-Cache,X-Amzn-AX-Treatment,User-Agent"
    };
    const statusCode = 200;
    const contentType = "text/plain;charset=cp1252";

    var COMMA_DELIMITER = ',';

    return new Promise((resolve, reject) => {
      parseCSVFile(responseString, COMMA_DELIMITER, function (error, response) {
        if (error) {
          reject(error);
        }
        resolve(response);
      })
    });
  };
  this.mockupTabDelimiteReport = async function(sellerId, mwsAuthToken, marketplaceidList) {
    const headers = {
      "server": "Server",
      "date": "Sun, 16 Aug 2020 03:30:58 GMT",
      "content-type": "text/plain;charset=Cp1252",
      "content-length": "961",
      "connection": "close",
      "x-amz-rid": "WGWXM1ENR56CVDYS0XQS",
      "x-mws-quota-max": "60.0",
      "x-mws-quota-remaining": "57.0",
      "x-mws-quota-resetson": "2020-08-16T04:09:00.000Z",
      "content-md5": "GUhXEnqSAjqE4ay1XDdkUA==",
      "x-mws-response-context": "aOsN4kFxkvluCLHKBSBLOltUkgFzZjCaYJ25ykDFcsVW0cVvPp3DLXvt6eIYdjJn/qyny5gg/6o=, ps1Q0/mukl/acPWAdzJyIkYt0CrrIQ19xgddunEFmLEzy7BpQxAPkRkfTQeO5gdKFTUstCZQTRI=",
      "x-amz-request-id": "f50fdd9f-ac49-467d-859c-a49f40575861",
      "x-mws-request-id": "f50fdd9f-ac49-467d-859c-a49f40575861",
      "x-mws-timestamp": "2020-08-16T03:30:58.488Z",
      "vary": "Content-Type,Accept-Encoding,X-Amzn-CDN-Cache,X-Amzn-AX-Treatment,User-Agent"
    };
    const statusCode = 200;
    const contentType = "text/plain;charset=cp1252";

    var TAB_DELIMITER = '\t';
    var COMMA_DELIMITER = ',';

    return new Promise((resolve, reject) => {
      parseCSVFile(responseString, TAB_DELIMITER, function (error, response) {
        if (error) {
          reject(error);
        }
        resolve(response);
      })
    });
  };
  this.mockupCall = async function(sellerId, mwsAuthToken, marketplaceidList) {
    const xmlParser = new xml2js.Parser({
      mergeAttrs: true,
      explicitArray: false,
      emptyTag: {},
      charkey: 'Value'
    });

    return xmlParser.parseStringPromise(responseString).then((response, error) => {
      const data = response[action + "Response"][action + "Result"];
      const headers = {
        "server": "Server",
        "date": "Sat, 15 Aug 2020 09:21:17 GMT",
        "content-type": "text/xml",
        "content-length": "346",
        "connection": "close",
        "x-amz-rid": "E56RY7VAG01YPNFXSADZ",
        "x-amz-date": "Sat, 15 Aug 2020 09:21:17 GMT",
        "x-amzn-authorization": "AAA identity=com.amazon.aaa.MarketplaceWebServiceOrders.AndromedaControlService.amzn1.aaa.id.qhz3ylg755gkejyk5sh44qm3wy.Default/1, Operation=ListOrders, Service=MarketplaceWebServiceOrders, Encrypted=false, SignedHeaders=X-Amz-Date, Algorithm=HmacSHA256, Signed=true, Signature=BxWUZF+pkheV1uj2w3pndVOEnq4E5N31AezcmJIhjWg=,RelationshipVersion=0",
        "x-mws-request-id": "b30edf4f-2364-4409-9478-74716d408865",
        "x-mws-timestamp": "2020-08-15T09:21:17.630Z",
        "x-mws-response-context": "4jgflZqc5TJKstGc//2YFv4SA28/0FbpJVj+hhbpcQ3IcJfmvC+d5kPq+XyIT5E6du9pOrAvIGE=",
        "vary": "Content-Type,Accept-Encoding,X-Amzn-CDN-Cache,X-Amzn-AX-Treatment,User-Agent"
      };
      const statusCode = 200;
      const contentType = "text/xml";
      const r = Object.assign(data, {
        "ResponseMetadata": response.ResponseMetadata || {},
        "StatusCode": statusCode,
        "Headers": headers,
      });
      return r;
    });
  }
};

module.exports = AmazonMwsStub;